// ==UserScript==
// @name         名师网荣誉批量通过工具
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  在名师网荣誉列表页面添加批量通过功能
// @author       zjlester
// @match        https://ms.zjer.cn/index.php?r=studio/admin/HonourList*
// @match        https://ms.zjer.cn/index.php?r=studio/admin/honourList*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 等待DOM加载完成
    function waitForDOM() {
        if (document.querySelector('a[onclick*="honourclick"]')) {
            initBatchApproveButton();
        } else {
            setTimeout(waitForDOM, 500);
        }
    }

    // 初始化批量通过按钮
    function initBatchApproveButton() {
        // 查找目标元素
        const targetElement = document.querySelector('p.fl[style*="margin-left:25px"]');
        if (!targetElement) {
            console.log('未找到目标元素');
            return;
        }

        // 创建批量通过按钮
        const batchButton = document.createElement('input');
        batchButton.type = 'button';
        batchButton.value = '批量通过';
        batchButton.className = 'btn_blue';
        batchButton.style.marginLeft = '10px';
        
        // 添加点击事件
        batchButton.addEventListener('click', handleBatchApprove);
        
        // 将按钮添加到目标元素中
        targetElement.appendChild(batchButton);
    }

    // 创建进度信息框
    function createProgressBox() {
        const progressBox = document.createElement('div');
        progressBox.id = 'batch-progress-box';
        progressBox.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 300px;
            padding: 20px;
            background: white;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            z-index: 10000;
            text-align: center;
            font-family: Arial, sans-serif;
        `;
        
        progressBox.innerHTML = `
            <h3>批量处理中...</h3>
            <p>正在处理：<span id="current-item">0</span>/<span id="total-items">0</span></p>
            <p>状态：<span id="status-text">准备中...</span></p>
            <div id="progress-bar-container" style="width: 100%; height: 20px; background-color: #f0f0f0; border-radius: 10px; margin: 10px 0;">
                <div id="progress-bar" style="width: 0%; height: 100%; background-color: #4CAF50; border-radius: 10px; transition: width 0.3s;"></div>
            </div>
            <button id="cancel-button" style="margin-top: 10px; background-color: #f44336; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;">取消</button>
        `;
        
        document.body.appendChild(progressBox);
        
        // 添加取消按钮事件
        document.getElementById('cancel-button').addEventListener('click', function() {
            if (confirm('确定要取消批量操作吗？')) {
                document.body.removeChild(progressBox);
                window.batchApproveCancelled = true;
            }
        });
        
        return progressBox;
    }

    // 更新进度信息
    function updateProgress(current, total, status) {
        const progressBox = document.getElementById('batch-progress-box');
        if (!progressBox) return;
        
        document.getElementById('current-item').textContent = current;
        document.getElementById('total-items').textContent = total;
        document.getElementById('status-text').textContent = status;
        
        const progressPercentage = total > 0 ? (current / total) * 100 : 0;
        document.getElementById('progress-bar').style.width = progressPercentage + '%';
    }

    // 关闭进度框
    function closeProgressBox() {
        const progressBox = document.getElementById('batch-progress-box');
        if (progressBox) {
            document.body.removeChild(progressBox);
        }
    }

    // 处理批量通过逻辑
    function handleBatchApprove() {
        // 获取所有通过链接
        const approveLinks = document.querySelectorAll('a[onclick*="honourclick"]');
        
        if (approveLinks.length === 0) {
            alert('未找到需要通过的项目');
            return;
        }
        
        // 确认操作
        if (!confirm(`确定要批量通过 ${approveLinks.length} 个项目吗？`)) {
            return;
        }
        
        // 初始化取消标志
        window.batchApproveCancelled = false;
        
        // 创建并显示进度框
        createProgressBox();
        updateProgress(0, approveLinks.length, '开始处理...');
        
        // 遍历所有通过链接并模拟点击
        approveLinks.forEach((link, index) => {
            // 添加延时，避免请求过于频繁
            setTimeout(() => {
                // 检查是否已取消
                if (window.batchApproveCancelled) {
                    updateProgress(index, approveLinks.length, '操作已取消');
                    setTimeout(closeProgressBox, 1000);
                    return;
                }
                
                // 提取onclick中的参数
                const onclickAttr = link.getAttribute('onclick');
                const match = onclickAttr.match(/honourclick\((\d+),'(in)'\)/);
                
                if (match) {
                    const id = match[1];
                    // 更新进度
                    updateProgress(index + 1, approveLinks.length, `正在处理ID: ${id}`);
                    // 直接发送请求而不是调用onclick函数
                    sendApproveRequest(id, index, approveLinks.length);
                }
            }, index * 500); // 每500毫秒处理一个
        });
    }

    // 发送通过请求
    function sendApproveRequest(id, index, total) {
        // 检查是否已取消
        if (window.batchApproveCancelled) {
            if (index === total - 1) {
                setTimeout(closeProgressBox, 1000);
            }
            return;
        }
        
        const xhr = new XMLHttpRequest();
        const url = `https://ms.zjer.cn/index.php?r=studio/admin/honourDel&id=${id}&act=in`;
        
        xhr.open('GET', url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    console.log(`成功处理第 ${index + 1}/${total} 个项目 (ID: ${id})`);
                    // 如果是最后一个请求，提示完成
                    if (index === total - 1 && !window.batchApproveCancelled) {
                        updateProgress(total, total, '处理完成');
                        setTimeout(() => {
                            closeProgressBox();
                            alert('批量通过处理完成，页面即将刷新');
                            // 刷新页面以显示更新后的状态
                            setTimeout(() => {
                                location.reload();
                            }, 1000);
                        }, 500);
                    }
                } else {
                    console.error(`处理项目失败 (ID: ${id})`);
                    updateProgress(index + 1, total, `处理失败 ID: ${id}`);
                }
            }
        };
        xhr.send();
    }

    // 页面加载完成后执行
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', waitForDOM);
    } else {
        waitForDOM();
    }
})();